<!DOCTYPE html>
<html>
<head>
  <title>Ethereum Medical Record DApp</title>
  <meta charset="utf-8">
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
  <script type="text/javascript" src="javascripts/jquery-1.8.1.min.js"></script>
  <script type="text/javascript" src="javascripts/web3.min.js"></script>
  <script type="text/javascript" src="javascripts/bootstrap.min.js"></script>
  <script type="text/javascript" src="javascripts/jsbn/jsbn.js"></script>
  <script type="text/javascript" src="javascripts/jsbn/jsbn2.js"></script>
  <script type="text/javascript" src="javascripts/jsbn/prng4.js"></script>
  <script type="text/javascript" src="javascripts/jsbn/rng.js"></script>
  <script type="text/javascript" src="javascripts/paillier.js"></script>
  <style type="text/css">
		div.result {
			background-color: #cccccc;
			word-wrap: break-word;
		}
		.cyphertext {
			 word-wrap: break-word;
		}
        div.alert {
            color: red;
            font-size: 18px;    
            background-color: #cccccc;     
        }
  </style>
</head>
<body class="container">
    <h1>Medical Record in Ethereum <small> Homomorphic Encryption Demo</small></h1>
  <div class="table-responsive">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>Patient Vitals</th>
          <th>New Input</th>
          <th>Prior</th>
          <th>Current</th>
          <th>Change</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Pulse</td>
          <td><input type="text" id="pulse_val"/></td>
          <td id="pulse_pv"></td>
          <td id="pulse_nv"></td>
          <td id="pulse_ch"></td>
        </tr>
        <tr>
          <td>Respiratory Rate</td>
          <td><input type="text" id="resp_val"/></td>
          <td id="resp_pv"></td>
          <td id="resp_nv"></td>
          <td id="resp_ch"></td>
        </tr>
        <tr>
          <td>Body Temperature</td>
          <td><input type="text" id="temp_val"/></td>
          <td id="temp_pv"></td>
          <td id="temp_nv"></td>
          <td id="temp_ch"></td>  
        </tr>
        <tr>
          <td>BP Systolic</td>
          <td><input type="text" id="bpsys_val"/></td>
          <td id="bps_pv"></td>
          <td id="bps_nv"></td>
          <td id="bps_ch"></td>
        </tr>
        <tr>
          <td>BP Diastolic</td>
          <td><input type="text" id="bpdias_val"/></td>
          <td id="bpd_pv"></td>
          <td id="bpd_nv"></td>
          <td id="bpd_ch"></td>
        </tr>
        <tr>
          <td>Weight</td>
          <td><input type="text" id="weight_val"/></td>
          <td id="weight_pv"></td>
          <td id="weight_nv"></td>
          <td id="weight_ch"></td>
        </tr>
        <tr>
          <td>Height (feet)</td>
          <td><input type="text" id="htft_val"/></td>
          <td id="htft_pv"></td>
          <td id="htft_nv"></td>
          <td id="htft_ch"></td>
        </tr>
        <tr>
          <td>Height (inches)</td>
          <td><input type="text" id="htin_val"/></td>
          <td id="htin_pv"></td>
          <td id="htin_nv"></td>
          <td id="htin_ch"></td>
        </tr>
      </tbody>
    </table>
    <div id="msg" class="alert"></div>
  </div>
  <a href="#" onclick="setRecord()" class="btn btn-primary">Update</a>
  <p></p>
  <h1>Vitals in Current Block</h1>
  <div class="table-responsive">
  <table class="table table-bordered">
    <thead>
        <tr>
            <th>Vitals</th>
            <th>Current</th>
            <th>Encrypted</th>
        </tr>
    </thead>
    <tbody>
        <tr>
          <td>Pulse</td>
          <td id="pulse_dec"></td>
          <td id="pulse_en"></td>
        </tr>
        <tr>
          <td>Respiratory Rate</td>
          <td id="resp_dec"></td>
          <td id="resp_en"></td>
        </tr>
        <tr>
          <td>Temperature</td>
          <td id="temp_dec"></td>
          <td id="temp_en" ></td>
        </tr>
        <tr>
          <td>BP Systolic</td>
          <td id="bps_dec"></td>
          <td id="bps_en"></td>
        </tr>
        <tr>
          <td>BP Diastolic</td>
          <td id="bpd_dec"></td>
          <td id="bpd_en"></td>
        </tr>
        <tr>
          <td>Weight</td>
          <td id="weight_dec"></td>
          <td id="weight_en"></td>
        </tr>
        <tr>
          <td>Height Ft</td>
          <td id="hft_dec"></td>
          <td id="hft_en"></td>
        </tr>
        <tr>
          <td>Height in</td>
          <td id="hin_dec"></td>
          <td id="hin_en"></td>
        </tr>
    </tbody>
  </table>
  </div>
<script type="text/javascript">
var keys, encA, encB, encAB, encABC;

var prior_vitals = {"Pulse": "pulse_pv", "Respiration": "resp_pv", "Temperature": "temp_pv", "BP-sys":"bps_pv", "BP-dias": "bpd_pv", "Weight": "weight_pv", "Height-ft": "htft_pv", "Height-in": "htin_pv"}
var cur_vitals = {"Pulse": "pulse_nv", "Respiration": "resp_nv", "Temperature": "temp_nv", "BP-sys":"bps_nv", "BP-dias": "bpd_nv", "Weight": "weight_nv", "Height-ft": "htft_nv", "Height-in": "htin_nv"}
var diff_vitals = {"Pulse": "pulse_ch", "Respiration": "resp_ch", "Temperature": "temp_ch", "BP-sys":"bps_ch", "BP-dias": "bpd_ch", "Weight": "weight_ch", "Height-ft": "htft_ch", "Height-in": "htin_ch"}
var input_vitals = {"Pulse": "pulse_val", "Respiration": "resp_val", "Temperature": "temp_val", "BP-sys":"bpsys_val", "BP-dias": "bpdias_val", "Weight": "weight_val", "Height-ft": "htft_val", "Height-in": "htin_val"}
var dec_vitals = {"Pulse": "pulse_dec", "Respiration": "resp_dec", "Temperature": "temp_dec", "BP-sys":"bps_dec", "BP-dias": "bpd_dec", "Weight": "weight_dec", "Height-ft": "hft_dec", "Height-in": "hin_dec"}
var enc_vitals = {"Pulse": "pulse_en", "Respiration": "resp_en", "Temperature": "temp_en", "BP-sys":"bps_en", "BP-dias": "bpd_en", "Weight": "weight_en", "Height-ft": "hft_en", "Height-in": "hin_en"}

var pubkey = '85770143673266196695769522192698601211847657470798363386562731378749298778213';
var privkey = '42885071836633098347884761096349300605628581318200097492510591026026431898214';
var numbits = 256;
var vit = new Array();
var v_array = new Array();
var curr = new Array();
var prio = new Array();

var Medical_record = contract(medical_record_artifacts);

function keygen(){
    keys = paillier.generateKeys(numbits);
    keys.pub.n = parseInt(pubkey);
    keys.sec.lambda = parseInt(privkey);
    encPaillier();
}

function encPaillier(){
  let vnames = Object.keys(enc_vitals);
  for (var i = 0; i < vnames.length; i++){
        let in_vital = vnames[i];
        let vital = parseInt($('#' + input_vitals[in_vital]).val());
        encA = keys.pub.encrypt(nbv(vital));
        $("#" + enc_vitals[in_vital]).html(encA.toString());
  }
}


function readInput(){
    var vnames = Object.keys(input_vitals);
    for (var i = 0; i< vnames.length; i++){
        let in_vital = vnames[i];
        v_array[i] = $('#' + input_vitals[in_vital]).val();
    }
    console.log(v_array);
    return v_array;
}


window.setRecord = function(){
    var inp = readInput();
    try{
        $("#msg").html("New Medical Vitals submitted. The Display will update when the transaction has been recorded on the blockchain. Please wait....")
        Medical_record.deployed().then(function(contractInstance){
            contractInstance.updatenewVitals(inp, {from: web3.eth.accounts[0]}).then(function(){
                $("#msg").html("New Vitals Successfully Recorded in Ethereum Blockchain..."); 
                updatePage();
            });
        }); 
    }catch (err) {
        console.log(err);
    } 
}


function updatePage(){
    console.log("Updating Page");
    Medical_record.deployed().then(function(contractInstance){
        contractInstance.getRecord.call('current',{from: web3.eth.accounts[0]}).then(function(v){
            console.log("Updating Current");
            let vnames = Object.keys(cur_vitals);
            for (var i = 0; i < vnames.length; i++){
                curr[i] = parseInt(v[i].toString());
                let vital = vnames[i];
                $("#" + cur_vitals[vital]).html(v[i].toString());
                $("#" + dec_vitals[vital]).html(v[i].toString());
            }
        });
        contractInstance.getRecord.call('prior',{from: web3.eth.accounts[0]}).then(function(v){
            console.log("Updating Prior");
            let vnames = Object.keys(prior_vitals);
            for (var i = 0; i < vnames.length; i++){
                prio[i] = parseInt(v[i].toString());
                let vital = vnames[i];
                $("#" + prior_vitals[vital]).html(v[i].toString());
                $("#" + diff_vitals[vital]).html(curr[i] - v[i]);
            }
        });
    })
}

$(document).ready(function() {
    if (typeof web3 !== 'undefined') {
        console.warn("Using web3 detected from external source like Metamask")
                //Use Mist/MetaMask's provider
        window.web3 = new Web3(web3.currentProvider);
    } else {
        console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
        window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
//    keygen();
    Medical_record.setProvider(web3.currentProvider);
    updatePage();
});
</script>  
</body>
</html>
